package com.skycan.plc.adapter.netty;

import com.skycan.plc.adapter.config.AppConfig;
import com.skycan.plc.adapter.netty.handler.DeviceChannelInitializer;
import com.skycan.plc.adapter.service.DeviceService;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Netty TCP服务器
 */
public class NettyServer {
    private static final Logger logger = LoggerFactory.getLogger(NettyServer.class);

    private final int port;
    private final DeviceService deviceService;

    private EventLoopGroup bossGroup;
    private EventLoopGroup workerGroup;
    private ChannelFuture channelFuture;

    public NettyServer(DeviceService deviceService) {
        this.port = AppConfig.getInstance().getServerPort();
        this.deviceService = deviceService;
    }

    /**
     * 启动服务器
     */
    public void start() throws Exception {
        bossGroup = new NioEventLoopGroup(1);
        workerGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new DeviceChannelInitializer(deviceService))
                    .childOption(ChannelOption.SO_KEEPALIVE, true);

            // 绑定端口，启动服务器
            channelFuture = b.bind(port).sync();
            logger.info("Netty服务器启动成功，监听端口: {}", port);

            // 等待服务器套接字关闭
            // channelFuture.channel().closeFuture().sync();
        } catch (Exception e) {
            logger.error("Netty服务器启动失败: {}", e.getMessage());
            shutdown();
            throw e;
        }
    }

    /**
     * 关闭服务器
     */
    public void shutdown() {
        logger.info("正在关闭Netty服务器...");

        if (channelFuture != null) {
            channelFuture.channel().close();
        }

        if (bossGroup != null) {
            bossGroup.shutdownGracefully();
        }

        if (workerGroup != null) {
            workerGroup.shutdownGracefully();
        }

        logger.info("Netty服务器已关闭");
    }
}